package cn.com.pagoda.ideplugin.ui;

import cn.com.pagoda.ideplugin.service.ExcelConversionService;
import com.intellij.openapi.actionSystem.AnActionEvent;
import org.json.JSONObject;

import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;

/**
 * @author 李涌清 on 2023-05-06
 */
public class ExcelConversionPanel extends Component implements ActionListener {

    private final AnActionEvent anActionEvent;

    /**
     * 按钮
     */
    private final JButton convertButton, chooseFileButton, copyButton, clearButton, exampleButton;
    private final JPanel panel;
    /**
     * 显示文本框
     */
    private final JTextArea jsonTextArea, excelTextArea;
    /**
     * 区域
     */
    private final JPanel upperPanel,middlePanel,lowerPanel;
    /**
     * 加载文本
     */
    private final JLabel loadingLabel;
    private final ExcelConversionService service;

    public ExcelConversionPanel(AnActionEvent anActionEvent, JPanel mainPanel) {
        this.anActionEvent = anActionEvent;
        this.service = new ExcelConversionService();

        panel = new JPanel(new GridBagLayout());
        // 创建上部区域，包括文本区域以粘贴Excel数据
        upperPanel = new JPanel(new BorderLayout());
        JLabel label = new JLabel("Please paste the Excel data here");
        label.setForeground(Color.RED);
        label.setHorizontalAlignment(JLabel.CENTER);
        upperPanel.add(label, BorderLayout.NORTH);
        excelTextArea = new JTextArea();
        upperPanel.add(new JScrollPane(excelTextArea), BorderLayout.CENTER);

        //加载提醒
        loadingLabel = new JLabel("loading...");
        loadingLabel.setVisible(false);

        // 创建中间区域，包括开始转换按钮、选择文件按钮、复制结果按钮和清空按钮
        middlePanel = new JPanel(new FlowLayout());
        convertButton = new JButton("Start Conversion");
        chooseFileButton = new JButton("Choose File");
        copyButton = new JButton("Copy Result");
        clearButton = new JButton("Clear");
        exampleButton = new JButton("View Sample");
        this.addMiddlePanel();

        // 创建下部区域，包括文本区域以显示JSON数据
        lowerPanel = new JPanel(new BorderLayout());
        jsonTextArea = new JTextArea();
        lowerPanel.add(new JScrollPane(jsonTextArea), BorderLayout.CENTER);

        // 将组件添加到主面板中，并使用约束
        this.addGridBagConstraints();

        mainPanel.add(panel, getClass().getSimpleName());
    }

    private void addMiddlePanel() {
        convertButton.addActionListener(this);
        chooseFileButton.addActionListener(this);
        copyButton.addActionListener(this);
        clearButton.addActionListener(this);
        exampleButton.addActionListener(this);
        middlePanel.add(convertButton);
        middlePanel.add(chooseFileButton);
        middlePanel.add(copyButton);
        middlePanel.add(clearButton);
        middlePanel.add(exampleButton);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        addLoadingLabel("loading...", true);
        if (e.getSource() == convertButton) {
            // 处理转换操作，并在文本区域中显示JSON数据
            handleConversion();
        } else if (e.getSource() == chooseFileButton) {
            handleChooseFile();
        } else if (e.getSource() == copyButton) {
            handleCopy();
            return;
        } else if (e.getSource() == clearButton) {
            handleClear();
        } else if (e.getSource() == exampleButton) {
            handleExample();
        }
        addLoadingLabel("Loading completed！", false);
    }

    /**
     * 处理转换操作，并在文本区域中显示JSON数据
     */
    private void handleConversion() {
        String excelText = excelTextArea.getText();
        JSONObject jsonData = service.textConvert(excelText);
        jsonTextArea.setText(jsonData.toString());
    }

    /**
     * 选择Excel文件并将其内容显示在文本区域中
     */
    private void handleChooseFile() {
        excelTextArea.setText("File selection is being converted... ...");
        JFileChooser fileChooser = new JFileChooser();
        int result = fileChooser.showOpenDialog(panel);
        if (result == JFileChooser.APPROVE_OPTION) {
            File file = fileChooser.getSelectedFile();
            JSONObject jsonData = null;
            try {
                jsonData = service.convert(file);
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(panel, "Conversion failure：" + ex.getMessage());
            }
            jsonTextArea.setText(jsonData.toString());
        }
        excelTextArea.setText("");
    }

    /**
     * 获取文本区域中的JSON数据，并将其复制到剪贴板中
     */
    private void handleCopy() {
        String jsonData = jsonTextArea.getText();
        StringSelection selection = new StringSelection(jsonData);
        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
        clipboard.setContents(selection, null);
        addLoadingLabel("replicated data", true);
    }

    /**
     * 清空所有文本区域
     */
    private void handleClear() {
        excelTextArea.setText("");
        jsonTextArea.setText("");
    }

    private void handleExample() {
        String text = "field1\tfield2\tfield3\tfield4\tfield5\tfield6\n" +
                "1\t2\t3\t4\t5\t6\n" +
                "21\t22\t23\t24\t25\t26\n" +
                "31\t32\t33\t34\t35\t36\n" +
                "41\t42\t43\t44\t45\t46\n" +
                "51\t52\t53\t54\t55\t56\n" +
                "61\t62\t63\t64\t65\t66";
        excelTextArea.setText(text);
        JSONObject jsonData = service.textConvert(text);
        jsonTextArea.setText(jsonData.toString());
    }

    /**
     * 加载提示语
     * @param loadingText 提示语
     * @param isShowText 是否显示提示语
     */
    private void addLoadingLabel (String loadingText, boolean isShowText) {
        loadingLabel.setText(loadingText);
        loadingLabel.setVisible(isShowText);
    }

    private void addGridBagConstraints() {
        GridBagConstraints gbc = new GridBagConstraints();

        addPanelToLayout(upperPanel, gbc, GridBagConstraints.BOTH, 0, 0, 1, 1);
        addPanelToLayout(loadingLabel, gbc, GridBagConstraints.NONE, 0, 1, 0, 0);
        addPanelToLayout(middlePanel, gbc, GridBagConstraints.NONE, 0, 2, 0, 0);
        addPanelToLayout(lowerPanel, gbc, GridBagConstraints.BOTH, 0, 3, 1, 1);
    }

    private void addPanelToLayout(JComponent component, GridBagConstraints gbc, int fill, int gridx, int gridy, double weightx, double weighty) {
        gbc.gridx = gridx;
        gbc.gridy = gridy;
        gbc.fill = fill;
        gbc.weightx = weightx;
        gbc.weighty = weighty;
        panel.add(component, gbc);
    }

}

